import { Evented } from "../event/Evented";
import { any } from "./logic";
import { guid } from "./utils";

class Base extends Evented {
    constructor(opts = {}) {
        super();
        this._id = any(opts.id, guid());
        this.name = any(opts.name, "");
        this.state = {};
        this.watchers = [];
        this.setState(false);
        this.autoUpdate = false;
    }

    update() {//子类实现

    }
    /**
     * 设置参数状态
     * @param {Number} v 参数状态 false,true
     * @param {String} key 参数名,缺省"x",标识整体状态。
     */
    setState(v, key = "x") {
        this.state[key] = v;
    }
    getState(key = "x") {
        return this.state[key];
    }
    /**
     * id
     * @property {String}
     * @readonly
     */
    get id() {
        return this._id;
    }
    get name() {
        return this._name;
    }
    /**
     * name
     * @property {String}
     */
    set name(v) {
        this._name = v;
        return this;
    }
    /**
     * 事件机制中添加观察者。
     * @method
     * @param {*}  
     */
    bind(watcher) {
        let has = false
        for (let i = 0; i < this.watchers.length; i++) {
            if (this.watchers[i] == watcher) {
                has = true;
                break;
            }
        }
        if (!has) {
            this.watchers.push(watcher);
        }
    }
    /**
    * 事件机制中解除观察者。
    * @method
    * @param {*} obj 
    */
    unBind(watcher) {
        const index = this.watchers.indexOf(watcher);
        if(index!==-1){
            this.watchers.splice(index, 1);
        }
        
    }
    /**
    * 事件机制中清除所有观察者。
    * @method
    * @param {watcher} obj 
    */
    clear() {
        this.watchers = [];
    }
    notice(v) {
        for (let i = 0, len = this.watchers.length; i < len; i++) {
            this.watchers[i].update(v);
        }
    }
    /**
     * 销毁方法
     * @method
     */
    destroy() {
        this._id = null;
        this._type = null;
        this._name = null;
        this._state = null;
        this._autoUpdate = null;
        this._watchers=null;
    }
}

export { Base }